package com.rybbaby.tss.platform.sysPreserve.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.FileUtils;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author 谢进伟
 * @description 文件维护
 * @createDate 2017/3/3 10:51
 */
@Controller
@RequestMapping(value = "preserve/file")
public class FilePreserveController extends BaseController {

    @RequestLog(content = "项目发布文件维护")
    @RequestMapping(value = "fileAceEdit")
    public ModelAndView databaseAceEdit() {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("fileAceEditView"));
        mav.addObject("mode", "text");
        return mav;
    }

    @RequestLog(content = "项目发布文件维护")
    @RequestMapping(value = "projectDirTree")
    public ModelAndView databaseTablesTree() {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("projectDirTreeView"));
        String projectDir = getSession().getServletContext().getRealPath("/");
        mav.addObject("projectDir", projectDir);
        return mav;
    }

    @ResponseBody
    @RequestLog(content = "读取文件")
    @RequestMapping(value = "redFile", method = RequestMethod.GET)
    public ModelAndView redFile(@RequestParam(required = true) String filePath) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("redFileView"));
        File file = new File(filePath);
        if (file.exists()) {
            String suffix = "." + StringUtils.substringAfterLast(filePath, ".");
            List<String> canUpdateFileSuffixs = new ArrayList<String>();
            canUpdateFileSuffixs.add(".ftl");
            canUpdateFileSuffixs.add(".jsp");
            canUpdateFileSuffixs.add(".jspf");
            canUpdateFileSuffixs.add(".html");
            canUpdateFileSuffixs.add(".xml");
            canUpdateFileSuffixs.add(".tld");
            canUpdateFileSuffixs.add(".css");
            canUpdateFileSuffixs.add(".js");
            canUpdateFileSuffixs.add(".json");
            canUpdateFileSuffixs.add(".java");
            canUpdateFileSuffixs.add(".sql");
            canUpdateFileSuffixs.add(".properties");
            canUpdateFileSuffixs.add(".text");
            if (canUpdateFileSuffixs.contains(suffix)) {
                try (FileInputStream input = new FileInputStream(filePath)) {
                    mav.addObject("fileContent", IOUtils.toString(input, StandardCharsets.UTF_8.toString()));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else {
                mav.addObject("fileContent", "此文件不支持在线更改!");
            }
        } else {
            mav.addObject("fileContent", "此文件不存在!");
        }
        return mav;
    }

    @ResponseBody
    @RequestLog(content = "保存文件")
    @RequestMapping(value = "saveFile", method = RequestMethod.POST)
    public String saveFile(@RequestParam(required = true) String filePath, String newContent) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("修改成功");
        File file = new File(filePath);
        if (file.exists()) {
            try (FileOutputStream output = new FileOutputStream(file)) {
                if (StringUtils.isNotBlank(newContent)) {
                    IOUtils.write(newContent.getBytes(StandardCharsets.UTF_8), output);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ajr.setResCode(-1);
            ajr.setResMsg("文件不存在!");
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "创建文件夹")
    @RequestMapping(value = "mkdirFolder", method = RequestMethod.GET)
    public String mkdirFolder(@RequestParam(required = true) String filePath, @RequestParam(required = true) String folderName) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("创建成功!");
        String separator = File.separator;
        File file = new File(filePath + separator + folderName);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                ajr.setResCode(-1);
                ajr.setResMsg("创建失败!");
            }
        } else {
            ajr.setResCode(-1);
            ajr.setResMsg("文件夹已存在!");
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "重命名文件夹")
    @RequestMapping(value = "renameFolder", method = RequestMethod.GET)
    public String renameFolder(@RequestParam(required = true) String filePath, @RequestParam(required = true) String folderName) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("重命名成功!");
        try {
            File srcDir = new File(filePath);
            if (srcDir.exists()) {
                File parentDir = srcDir.getParentFile();
                File destDir = new File(parentDir.getPath() + File.separator + folderName);
                if (!destDir.exists()) {
                    Arrays.stream(srcDir.listFiles()).forEach((File file) -> {
                        try {
                            FileUtils.moveFileToDirectory(file, destDir, true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                    FileUtils.deleteDirectory(srcDir);
                } else {
                    ajr.setResCode(-1);
                    ajr.setResMsg("文件夹已存在!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "删除文件夹")
    @RequestMapping(value = "deleteFolder", method = RequestMethod.GET)
    public String deleteFolder(@RequestParam(required = true) String filePath) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("删除文件夹成功!");
        try {
            File dir = new File(filePath);
            if (dir.exists()) {
                FileUtils.deleteDirectory(dir);
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("文件夹不存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "创建文件")
    @RequestMapping(value = "createFile", method = RequestMethod.GET)
    public String createFile(@RequestParam(required = true) String filePath, @RequestParam(required = true) String fileName) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("创建成功!");
        try {
            File file = new File(filePath + File.separator + fileName);
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    ajr.setResCode(-1);
                    ajr.setResMsg("文件创建失败!");
                }
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("文件已存在!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "重命名文件")
    @RequestMapping(value = "renameFile", method = RequestMethod.GET)
    public String renameFile(@RequestParam(required = true) String filePath, @RequestParam(required = true) String fileName) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("创建成功!");
        try {
            File srcFile = new File(filePath);
            File parentFile = srcFile.getParentFile();
            File destFile = new File(parentFile.getPath() + File.separator + fileName);
            if (!destFile.exists()) {
                FileUtils.moveFile(srcFile, destFile);
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("文件已存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "删除文件")
    @RequestMapping(value = "deleteFile", method = RequestMethod.GET)
    public String deleteFile(@RequestParam(required = true) String filePath) {
        AjaxJsonResponse ajr = new AjaxJsonResponse("创建成功!");
        try {
            File file = new File(filePath);
            if (file.exists()) {
                boolean newFile = file.delete();
                if (!newFile) {
                    ajr.setResCode(-1);
                    ajr.setResMsg("文件删除失败!");
                }
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("文件不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    @RequestLog(content = "显示上传文件页面")
    @RequestMapping(value = "showUploadFile", method = RequestMethod.GET)
    public ModelAndView showUploadFile() {
        ModelAndView mav = new ModelAndView("sysPage/platform/SysPreserve/fileUpload.html");
        mav.addObject("filePath", getParameter("filePath"));
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "upload")
    @RequestLog(content = "上传临时文件")
    public String uploadFile(MultipartHttpServletRequest request, @RequestParam(required = true) String filePath) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            File saveDir = new File(filePath);
            if (!saveDir.exists()) {
                FileUtils.forceMkdir(saveDir);
            }
            List<String> tempUploadFiles = new ArrayList<String>();
            MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
            multiFileMap.keySet().parallelStream().forEach((String key) -> {
                multiFileMap.get(key).parallelStream().forEach((MultipartFile multipartFile) -> {
                    String originalFilename = multipartFile.getOriginalFilename();// 原始名称
                    try (InputStream inputStream = multipartFile.getInputStream()) {
                        File newFile = new File(filePath + File.separator + originalFilename);
                        FileUtils.copyInputStreamToFile(inputStream, newFile);
                        tempUploadFiles.add(newFile.getPath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            });
            if (tempUploadFiles != null && !tempUploadFiles.isEmpty()) {
                ajr.setData(tempUploadFiles);
                return ajr.jsonResponse(true);
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("文件上传失败,请稍后再试!");
                return ajr.jsonResponse(false);
            }
        } catch (Exception e) {
            ajr.setResCode(-1);
            ajr.setResMsg(e.getMessage() == null ? "上传过程中发生异常!" : e.getMessage());
            return ajr.jsonResponse(false);
        }
    }
}
